package com.cn.ant.modules.school.web;

import com.cn.ant.common.config.Global;
import com.cn.ant.common.persistence.Page;
import com.cn.ant.common.utils.AjaxJson;
import com.cn.ant.common.utils.StringUtils;
import com.cn.ant.common.web.BaseController;
import com.cn.ant.modules.school.entity.SchoolMajor;
import com.cn.ant.modules.school.service.SchoolMajorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;

/**
 * 学校专业表Controller
 * @author AntDream
 * @version 2015-08-26
 */
@Controller
@RequestMapping(value = "${adminPath}/school/schoolMajor")
public class SchoolMajorController extends BaseController {

	@Autowired
	private SchoolMajorService schoolMajorService;

	@ModelAttribute
	public SchoolMajor get(@RequestParam(required=false) String id) {
		SchoolMajor entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = schoolMajorService.get(id);
		}
		if (entity == null){
			entity = new SchoolMajor();
		}
		return entity;
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(SchoolMajor schoolMajor, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<SchoolMajor> page = schoolMajorService.findPage(new Page<SchoolMajor>(request, response), schoolMajor); 
		model.addAttribute("page", page);
		return "modules/school/schoolMajorList";
	}

	@RequestMapping(value = "form")
	public String form(SchoolMajor schoolMajor, Model model) {
		model.addAttribute("schoolMajor", schoolMajor);
		return "modules/school/schoolMajorForm";
	}

	@RequestMapping(value = "save")
	@ResponseBody
	public AjaxJson save(@ModelAttribute(value = "majors") ArrayList<SchoolMajor> list, HttpServletRequest request, Model model) {
		AjaxJson jo = new AjaxJson();
		try {
			/*if (!beanValidator(model, schoolMajor)) {
				jo.setSuccess(false);
                jo.setMsg("数据校验失败,请重试!");
                return jo;
			} else {
			    schoolMajorService.save(schoolMajor);
			}*/
			msg = "保存学校专业关联信息成功";
			jo.setMsg(msg);
			jo.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			jo.setSuccess(false);
			jo.setMsg("操作失败,请联系管理员");
		}
		return jo;
	}
	
	@RequestMapping(value = "delete")
	public String delete(SchoolMajor schoolMajor, RedirectAttributes redirectAttributes) {
		schoolMajorService.delete(schoolMajor);
		addMessage(redirectAttributes, "删除学校专业关联信息成功");
		return "redirect:"+Global.getAdminPath()+"/school/schoolMajor/?repage";
	}
}